package com.atguigu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.base.BaseDao;
import com.atguigu.base.BaseServiceImpl;
import com.atguigu.dao.AdminRoleDao;
import com.atguigu.dao.RoleDao;
import com.atguigu.entity.AdminRole;
import com.atguigu.entity.Role;
import com.atguigu.service.RoleService;
import org.jboss.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lhh
 * @ClassName RoleServiceImpl
 * @date 2022/9/13 14:17
 */
@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl extends BaseServiceImpl<Role> implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private AdminRoleDao adminRoleDao;


    public List<Role> findAll() {
        return roleDao.findAll();
    }

    @Override
    protected BaseDao<Role> getEntityDao() {
        return roleDao;
    }

    public Map<String, Object> findRoleByAdminId(Long adminId) {
        //获取所有角色
        List<Role> allRoleList = roleDao.findAll();


        //获取当前用户的角色
        List<Long> roleIdList=adminRoleDao.findRoleByAdminId(adminId);

        //对角色进行分类
        List<Role> noAssignRoleList = new ArrayList<Role>();
        List<Role> assignRoleList = new ArrayList<Role>();
        for (Role role : allRoleList) {
            if(roleIdList.contains(role.getId())){
                assignRoleList.add(role);

            }else{
                noAssignRoleList.add(role);
            }
        }
        Map<String, Object> roleMap=new HashMap();
        roleMap.put("noAssignRoleList",noAssignRoleList);
        roleMap.put("assignRoleList",assignRoleList);
        return roleMap;
    }

    public void saveUserRoleRealtionShip(Long adminId, Long[] roleIds) {
        adminRoleDao.deleteByAdminId(adminId);

        for (Long roleId : roleIds) {
            if(!StringUtils.isEmpty(roleId)){
                AdminRole adminRole = new AdminRole();
                adminRole.setRoleId(roleId);
                adminRole.setAdminId(adminId);
                adminRoleDao.save(adminRole);
            }
        }
    }

}
